import re

from rest_framework import serializers
from areas.models import Area

# 0对模型类进行操作,所以使用模型类序列化器 ,
from users.models import Address


class AreaSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields=('id','name') # 2只需要返回id和name,name用来显示 ,前端获取id 再返回给后台,用来查询省下面的市,







class AddressSerializer(serializers.ModelSerializer):
    # 指定返回的省市区数据为省市区的名称(模型类中有外键,所以这里是关联嵌套序列化返回,)
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)


    # 指定接受前端传递的省市区id值(因为表是id值,但是序列化器生成的字段不是id值,所以添加如是)
    province_id = serializers.IntegerField(write_only=True)
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    # 验证手机号,(前端验证只需要验证手机号,因为用户输入什么,我就得保存什么,)
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            return serializers.ValidationError('手机号不正确')

        return value


    # 保存操作,
    def create(self, validated_data):
        # 因为在上面将user属性排除在外了,所以现在添加user属性
        validated_data['user'] = self.context['request'].user

        # 交给父类进行保存(因为保存是重写的)
        address = super().create(validated_data)

        return address

















                # class Address(serializers.ModelSerializer):
#
#     class Meta:
#         model=Addressmodel
#
#
#     def validate(self, attrs):
#
#
#
#     def create(self, validated_data):
#
#
#     def update(self, instance, validated_data):